# 测试 http://ld.heb.hsip.gov.cn/ 页面登录 

from selenium import webdriver  
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import NoSuchElementException  
from selenium.webdriver.support.ui import WebDriverWait  
from time import sleep    
import base64  
import io  
from PIL import Image  
from test8 import PyTesseractUtil


def main1():
    # 指定ChromeDriver的路径（如果你已经将其添加到系统环境变量中，则不需要这行代码）  
    driver_path = 'd:/apps/chromedriver/chromedriver.exe'  

    ser = Service()	
    ser.executable_path = driver_path

    options=Options()
    options.add_argument('–-incognito')
    options.add_argument('--disable-infobars')
    options.add_argument('--start-maximized')

    webdriver.Chrome(options=options,service=ser)  
    
    # 如果你已经将ChromeDriver添加到系统环境变量中，或者ChromeDriver在你的PATH中，你可以直接使用以下代码  
    driver = webdriver.Chrome()  
    
    # 请求Google主页  
    driver.get("http://ld.heb.hsip.gov.cn/")  


    elemsInputUsername=driver.find_elements(by=By.CSS_SELECTOR, value="input[name='username']")
    elemsInputPassword=driver.find_elements(by=By.CSS_SELECTOR, value="input[name='password']")
    elemsInputVerificateCode=driver.find_elements(by=By.CSS_SELECTOR, value="input[name='verificationCode']")

    if len(elemsInputUsername)==0 \
    or len(elemsInputPassword)==0 or len(elemsInputVerificateCode)==0: 
        print('页面未获得必要的控件，程序暂停')
        driver.quit()
        return
    

    # 检查是否成功获取元素  
    elemsInputUsername[0].send_keys("H13053400007_01")
    elemsInputPassword[0].send_keys("8129120@admin")

    icnt=0
    while True:

        # 检测页面表填 #tab-code
        elems1=driver.find_elements(by=By.ID, value="tab-code")

        if len(elems1)==0:
            print('当前不是登录页面')
            driver.refresh()
        else:

            strVerificateCode=getVerificateCode(drv1=driver)
            elemsInputVerificateCode[0].clear()
            elemsInputVerificateCode[0].send_keys(strVerificateCode)
            
            sleep(1)
            elemBtnLogins=driver.find_elements(by=By.CSS_SELECTOR, value="button.login-btn")
            if len(elemBtnLogins)>0:
                elemBtnLogins[0].click()  

            print('当前是登录页面')

        cookies = driver.get_cookies()

        icnt+=1
        print(f'#################{icnt}')
        for cookie in cookies:  
            print(f"Cookie Name: {cookie['name']}, Cookie Value: {cookie['value']}") 
            
        sleep(100)
    

# 让浏览器窗口保持打开状态，直到你手动关闭它  
# 如果你想在请求后自动关闭浏览器，可以取消注释以下代码  
# driver.quit()
        

def getVerificateCode(drv1):

    elemsImgVerificateCode=drv1.find_elements(by=By.CSS_SELECTOR, value="div.verificationCodeImage")

    if len(elemsImgVerificateCode)==0:
        return ''

    strBase64=getBase64Str(elemImg=elemsImgVerificateCode[0])
    # 将Base64字符串解码为二进制数据  
    img_data = base64.b64decode(strBase64)  
    
    # 将二进制数据转换为PIL Image对象  
    img = Image.open(io.BytesIO(img_data))  
    
    # 保存图片到文件  
    img.save('captcha.jpg')  

    # 获取验证码文字
    strVerificateCode = PyTesseractUtil().getText('captcha.jpg')

    # strVerificateCode='1234'
    return strVerificateCode

def getBase64Str(elemImg):
    style_attr = elemImg.get_attribute('style')  

    start_index = style_attr.find('base64,') + len('base64,')  
    end_index = style_attr.find(';', start_index)  
    if start_index != -1 and end_index != -1:  
        base64_img_data = style_attr[start_index:end_index]  
        return base64_img_data
    else:  
        print("Failed to find base64 data in the style attribute.")  
        return ''


if __name__ == '__main__':  
    main1()
